package com.toutoushidao.ssm.util;

import com.alibaba.fastjson.JSONObject;
import com.github.ontio.OntSdk;
import com.github.ontio.account.Account;
import com.github.ontio.common.Address;
import com.github.ontio.common.Helper;
import com.github.ontio.core.transaction.Transaction;
import com.github.ontio.crypto.SignatureScheme;
import com.github.ontio.smartcontract.neovm.abi.BuildParams;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class withdrawTest {

    private static final String DAPP_API = "http://dappnode1.ont.io";
    private static final String REST_PORT = "20334";
    private static final String OWNER_HASH = "6d062d85983eac16cf66a8b4e9951ff7e90bef99";
    private static final String PRIVATE_KEY = "Ky4wEkMWoDayW3naewdu4scAv3ofnEJotZkF9uxrQeYE665jsc1s";

    public static void main(String[] s) throws Exception {
        String address = "AQbWSFGQQRt7NfLJTV6zUAQFgVdZUBj6G7";
        BigDecimal amountBD = new BigDecimal("1.06");

        String acctPrivateKey = Helper.toHexString(Account.getPrivateKeyFromWIF(PRIVATE_KEY));
        Account payerAcct = new Account(Helper.hexToBytes(acctPrivateKey), SignatureScheme.SHA256WITHECDSA);
        OntSdk ontSdk = OntSdk.getInstance();
        ontSdk.setRestful(DAPP_API + ":" + REST_PORT);
        ontSdk.setDefaultConnect(ontSdk.getRestful());
        ontSdk.neovm().oep4().setContractAddress(OWNER_HASH);// 合约地址
        List paramList = new ArrayList<>();
        paramList.add("withDraw".getBytes());
        List args = new ArrayList();
        byte[] addressClass = Address.toScriptHash(Address.decodeBase58(address).toArray()).toArray();
        args.add(addressClass);
        // (ONG的精度是9，比如用户提取1个ONG，amount参数应该等于1000,000,000)
        BigDecimal ongAmount = amountBD.multiply(new BigDecimal("100000000")).setScale(0, BigDecimal.ROUND_UNNECESSARY);
        args.add(ongAmount.longValue());
        paramList.add(args);
        byte[] params = BuildParams.createCodeParamsScript(paramList);
        Transaction tx = ontSdk.vm().makeInvokeCodeTransaction(Helper.reverse(ontSdk.neovm().oep4().getContractAddress()), "withDraw", params, payerAcct.getAddressU160().toBase58(), 20000, 500);
        ontSdk.addSign(tx, payerAcct);
        Object result = ontSdk.getConnect().sendRawTransactionPreExec(tx.toHexString());
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(result);
        int state = jsonObject.getIntValue("State");
    }
}
